package com.jrx.anytxn.param.controller.partner;

import com.google.common.collect.Maps;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.dto.partner.PmMerchantTableReq;
import com.jrx.anytxn.param.dto.partner.PmMerchantTableRes;
import com.jrx.anytxn.param.plugins.DeleteLog;
import com.jrx.anytxn.param.plugins.DeleteLogHelper;
import com.jrx.anytxn.param.service.partner.IPmMerchantTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.service.InfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;


/**
 * 商户管理controller
 *
 * @author : zhenghaopu
 * 2020/2/24
 */
@Api(tags = "商户管理配置API接口")
@RestController
@RequestMapping(value = "/param/partner/merchant")
public class MerchantController {

    private static final Logger logger = LoggerFactory.getLogger(MerchantController.class);

    @Autowired
    private InfoService infoService;

    @Autowired
    private IPmMerchantTableService pmMerchantTableService;

    @ApiOperation(value = "根据租户ID和商户ID查询", notes = "根据租户ID和商户ID查询")
    @GetMapping(value = "/{tenantId}/{merchantId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "merchantId", value = "合作伙伴ID", required = true)
    })
    public TxnRespResult<PmMerchantTableRes> getById(@PathVariable String tenantId,
                                                     @PathVariable String merchantId) {
        TxnRespResult<PmMerchantTableRes> result = new TxnRespResult<>();
        PmMerchantTableRes res;
        try {
            res = pmMerchantTableService.getByTenIdIdAndMerchanId(tenantId, merchantId);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "新增合作伙伴信息", notes = "新增合作伙伴信息")
    @PostMapping("/")
    public TxnRespResult<PmMerchantTableRes> add(@RequestBody PmMerchantTableReq pmMerchantTableReq) {
        TxnRespResult<PmMerchantTableRes> result = new TxnRespResult<>();
        PmMerchantTableRes res;
        try{
            pmMerchantTableReq.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            pmMerchantTableReq.setUpdateBy(infoService.getUser().getUserName());
            res = pmMerchantTableService.addMerchantTable(pmMerchantTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "分页查询商户信息", notes = "分页查询商户信息")
    @GetMapping(value = "/pageNum/{pageNum}/pageSize/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = true)})
    public TxnRespResult<TxnPage<PmMerchantTableRes>> getAllPageByTenId(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        TxnRespResult<TxnPage<PmMerchantTableRes>> result = new TxnRespResult<>();
        try {
            String tenantId=String.valueOf(infoService.getUser().getProjectId());
            TxnPage<PmMerchantTableRes>  res = pmMerchantTableService.findAllPageByTenantId(pageNum, pageSize, tenantId);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID编辑商户信息", notes = "根据租户ID编辑商户信息")
    @PutMapping("/")
    public TxnRespResult<PmMerchantTableRes> modifyPmPartnerInfo(@RequestBody PmMerchantTableReq req) {
        TxnRespResult<PmMerchantTableRes> result = new TxnRespResult<>();
        PmMerchantTableRes res;
        try {
            req.setUpdateBy(infoService.getUser().getUserName());
            res = pmMerchantTableService.modifyPmMerchantTable(req);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID和合作伙伴ID删除信息", notes = "根据租户ID和合作伙伴ID删除信息")
    @DeleteMapping(value = "/{tenantId}/{merchantId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "merchantId", value = "合作伙伴ID", required = true)
    })
    public TxnRespResult<Boolean> removeByTenIdAndPartnerId(@PathVariable String tenantId, @PathVariable String merchantId) {
        TxnRespResult<Boolean> result = new TxnRespResult<>();
        try {
            DeleteLog deleteLog = new DeleteLog(infoService.getUser().getUserName());
            DeleteLogHelper.setDelleteHistory(deleteLog);

            Boolean flag =
                    pmMerchantTableService.removeByTenantIdAndMerchantId(tenantId, merchantId);
            result.getSuccess(flag);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        } finally {
            DeleteLogHelper.clearLocalHistory();
        }
        return result;
    }

    @ApiOperation(value = "根据租客号获取客户表内容", notes = "根据租客号获取客户表内容")
    @GetMapping(value = "/list")
    public TxnRespResult<HashMap<String, List<PmMerchantTableRes>>> getProductTableByTenId() {
        logger.debug("get Merchant start");
        TxnRespResult<HashMap<String, List<PmMerchantTableRes>>> result = new TxnRespResult<>();
        List<PmMerchantTableRes> pmMerchantTableResList;
        try {
            String tenantId = String.valueOf(infoService.getUser().getProjectId());
            pmMerchantTableResList = pmMerchantTableService.findAllByTenantId(tenantId);
            HashMap<String, List<PmMerchantTableRes>> sysCodeMap = Maps.newHashMap();
            sysCodeMap.put("listData", pmMerchantTableResList);
            result.getSuccess(sysCodeMap);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        logger.debug("get Merchant end");
        return result;
    }
}
